<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;

use Illuminate\Http\Request;
use \Illuminate\Support\Facades\Input;
use App\Models\Account\PlayerActModel;
use App\Models\Account\PlayerOnline;
use App\Models\Area;
use App\Models\Account\Behavior;

use App\Admin\Extra\Search\Html;

class PlayerController extends Controller
{

    // 账号列表
    public function anyListAccount()
    {
        $req_param = Input::all();
        PlayerActModel::getAccountByName();
        return Admin::content(function (Content $content)use($req_param) {

            $content->header('player account');
            $content->description('.....');

            $content->row(Html::append([
                Html::input('lastAreaId', 'Area Choice', '', $req_param['lastAreaId']),
                Html::likeRedirect('playerName', 'Player Name', url()->current(), $req_param['playerName']) ,
                Html::input('account', 'Account', '', $req_param['account']),
                Html::button('GO', url()->current(), 'search-filter'),
                Html::sjs(url()->current())
            ]));


            $grid = Admin::grid(PlayerActModel::class, function(Grid $grid){
                // 第一列显示id字段，并将这一列设置为可排序列
                $grid->account('account')->sortable();
                $grid->model()->orderBy('account', 'DESC');

                // 第二列显示title字段，由于title字段名和Grid对象的title方法冲突，所以用Grid的column()方法代替
                $grid->column('lastPlayerId');
                $grid->mainChannel('main channel');
                $grid->udid('Device');

                $area_data = \App\Models\Area::areaSelectData(0);
                $grid->lastAreaId('area')->display(function($value)use($area_data){
                    return $area_data[$value];
                });

                // 第三列显示director字段，通过display($callback)方法设置这一列的显示内容为users表中对应的用户名
                // $grid->director()->display(function($userId) {
                //     return User::find($userId)->name;
                // });

                // 第六列显示released字段，通过display($callback)方法来格式化显示输出
                $grid->identity('user identiy')->display(function ($identity) {
                    $arr = [0 => 'common', 1 => 'special', 2 => 'test', 1000 => 'robot'];
                    return isset($arr[$identity]) ?$arr[$identity] : '--';
                });

                // 下面为三个时间字段的列显示
                $grid->is_seal_number('seal state')->display(function($is_seal_number) {
                    $arr = [1 => 'unsealed', 2 => 'sealed'];
                    return isset($arr[$is_seal_number]) ?$arr[$is_seal_number]: $arr[1];
                });

                // 玩家角色名
                $grid->playerList('player name')->display(function($players){
                    $roles = json_decode($players, true);
                    return implode(' | ', array_column($roles?:[], 'playerName'));
                });
                $grid->createTime('Create Time')->sortable();
                $grid->lastLoginTime('lastLoginTime')->display(function($value){
                    return $value;
                })->sortable();
                $grid->ip('IP');
                // 禁用按钮
                $grid->disableCreateButton();

                // filter($callback)方法用来设置表格的简单搜索框
                $grid->filter(function ($filter)use($area_data) {

                    $filter->equal('account', 'account')->placeholder('user account');
                    // 模糊查询 注意
                    $filter->where(function ($query) {
                        $aids = \App\Models\Account\PlayerActModel::getAccountByName('', 'playerName');
                        //$query->where('account', $aids?:[]);
                        $query->where("account",'=', "58225");
                        //var_dump([$query, 'aa']);exit;
                    }, 'player name', 'playerName');
                    //$filter->scope('player_name', "player name")->whereIn('account', [58225]);

                    $filter->equal('lastPlayerId', 'player id')->placeholder('player id');
                    $filter->equal('udid', 'Device')->placeholder('iPhone');

                    $filter->in('mainChannel', 'main channel')->multipleSelect(Area::$area_mc);
                   
                    $filter->equal('lastAreaId', 'area chioce')->select($area_data);

                    // 设置created_at字段的范围查询
                    $filter->between('createTime', 'Created Time')->datetime();

                    //
                    $filter->disableIdFilter();
                });

                $grid->actions(function($actions){
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->append('<a href="'.url('admin/player/show?accountId='). $actions->row->account .'"><i class="glyphicon glyphicon-eye-open"></i></a>');
                    $actions->append('&nbsp;&nbsp;&nbsp;&nbsp;');
                    $actions->append(Html::button('<span class="glyphicon glyphicon-envelope" aria-hidden="true"></span>', '/admin/mail/create?id=0&area='.$actions->row->lastAreaId.'&receiver='.$actions->row->lastPlayerId, 'btn-goto btn-clear-all'));
                });

                $excel = new \App\Admin\Extensions\CustomExporter("account.".time(), PlayerActModel::getCustomExportHead(), null);
                $excel->setResouceFunc( function() {
                    return PlayerActModel::getCustomExportData();
                } );
                
                $grid->exporter($excel);
            });
            $content->row($grid->render());
            //$content->body(phpinfo());
        });

    }

    //账号详情
    public function anyShow(Request $request) {
        $accountId = $request->get('accountId');

        $info = PlayerActModel::detailPlayer($accountId);
        $data = [
            'title_act' => 'account operator',
        ];
        $data = array_merge($data, $info);
        return Admin::content(function (Content $content) use($data){
            $content->header('account manager');
            $content->description('.....');

            $content->row(view('admin.player.player_show', $data?:[]));

        });
    }

    public function anyRoleList(Request $request) {
        $req_param = Input::all();
        PlayerActModel::getAccountByName();
        return Admin::content(function (Content $content)use($req_param) {

            $content->header('player account');
            $content->description('.....');

            $content->row(Html::append([
                Html::input('area', 'Area Choice', '', $req_param['area']),
                Html::likeRedirect('player_name', 'Player Name', url()->current(), $req_param['playerName']) ,
                Html::input('account', 'Account', '', $req_param['account']),
                Html::button('GO', url()->current(), 'search-filter'),
                // Html::button('SyncPlayer', '/admin/command/sync-players?area='.Input::get('area'), 'btn-ajax'),///admin/command/sync-players?area=6
                Html::sjs(url()->current()),
            ]));


            $grid = Admin::grid(\App\Models\Account\PlayerRole::class, function(Grid $grid){
                // 第一列显示id字段，并将这一列设置为可排序列
                $grid->player_id('player_id')->sortable();
                $grid->account('account')->sortable();
                $grid->player_name('name');
                $grid->user_type('user type')->sortable();
                $grid->level('level')->sortable();

                $grid->thew('thew')->sortable();
                $grid->gold('gold')->sortable();
                $grid->diamond('diamond')->sortable();
                $grid->ticket('ticket')->sortable();

                $grid->vip_level('vip')->sortable();
                $grid->vip_exp('vip_exp')->sortable();
                $grid->hero_alias('hero')->display(function($value) {
                    return "<p>$this->hero_id</p>" . $value;
                });
                $grid->hero_skin_id('hero_skin_id');
                $grid->guild_id('guild_id');
                $grid->pet_id('pet_id')->sortable();

                // 第二列显示title字段，由于title字段名和Grid对象的title方法冲突，所以用Grid的column()方法代替
                // $grid->udid('Device');

                $area_data = \App\Models\Area::areaSelectData(0);
                $grid->area('area')->display(function($value)use($area_data){
                    return $area_data[$value];
                });

                // 第三列显示director字段，通过display($callback)方法设置这一列的显示内容为users表中对应的用户名
                // $grid->director()->display(function($userId) {
                //     return User::find($userId)->name;
                // });

                // 第六列显示released字段，通过display($callback)方法来格式化显示输出

                
                $grid->create_time('Create Time')->display(function($value){
                    return date("Y-m-d H:i:s", $value);
                })->sortable();
                
                // 禁用按钮
                $grid->disableCreateButton();

                // filter($callback)方法用来设置表格的简单搜索框
                $grid->filter(function ($filter)use($area_data) {

                    $filter->equal('account', 'account')->placeholder('user account');
                    // 模糊查询 注意
                    $filter->like('player_name', 'PlayerName');
                    //$filter->scope('player_name', "player name")->whereIn('account', [58225]);

                    $filter->equal('player_id', 'player id')->placeholder('player id');
                    $filter->equal('udid', 'Device')->placeholder('iPhone');

                    $filter->in('area', 'area')->multipleSelect($area_data );
                   

                    // 设置created_at字段的范围查询
                    $filter->between('create_time', 'Created Time')->datetime();

                    //
                    $filter->disableIdFilter();
                });

                $grid->actions(function($actions){
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->append('<a href="'.url('admin/player/show?accountId='). $actions->row->account .'"><i class="glyphicon glyphicon-eye-open"></i></a>');
                    $actions->append('&nbsp;&nbsp;&nbsp;&nbsp;');
                    $actions->append(Html::button('<span class="glyphicon glyphicon-envelope" aria-hidden="true"></span>', '/admin/mail/create?id=0&area='.$actions->row->area.'&receiver='.$actions->row->player_id, 'btn-goto btn-clear-all'));
                    $actions->append('&nbsp;&nbsp;&nbsp;&nbsp;');
                    $actions->append(Html::button('GM-CMD', '/admin/command?area='.$actions->row->area.'&pid='.$actions->row->player_id, 'btn-goto btn-warning btn-xs'));
                });

                $excel = new \App\Admin\Extensions\CustomExporter("account.".time(), PlayerActModel::getCustomExportHead(), null);
                $excel->setResouceFunc( function() {
                    return PlayerActModel::getCustomExportData();
                } );
                
                $grid->exporter($excel);
            });
            $content->row($grid->render());
            //$content->body(phpinfo());
        });
    }

    // 用户操作
    public function ajaxActPlayer(Request $request){
        $exAccount = new \App\Admin\Extra\Player\Account();
        $res = $exAccount->ajaxAct($request);
        return response($res, 200)
            ->header('Content-Type', 'application/json');
    }

    // 管理员添加的 用户体力列表
    public function anyListPower(){
        return Admin::content(function($content){
            $content->header('给玩家赠鸡腿，体力值列表');
            $content->description('.....');

        });

    }

    public function anyAddPower(){
        return Admin::content(function($content){
            $content->header('thew manager');
            $content->description('.....');

            $get = Input::all();

            $form = new Form();
            $form->divide();
            $form->text('playerId', '用户playerid')->rules('required|min:3')->help('请在玩家管理地方搜索到palyerId 再传到这里')->default($get['playerId']?:'');
            $form->text('area', '玩家所在的区域')->help('是玩家所在区域，必选项')->default($get['area']?:'');
            $form->number('thew', '鸡腿数量')->rules('required|min:3');
            $form->hidden('_token', '_token')->default(csrf_token());
            $form->action('/admin/player/api-power');
            // $form->disablePajax();

            $content->row($form);
        });
    }

    // 保存并发送体力给 game server
    public function apiPower(){
        $res = Input::all();
        $playerId = intval($res['playerId']);
        $area = intval($res['area']);
        $thew = intval($res['thew']);

        $playerInfo = \App\Models\Account\PlayerActModel::getPlayerInfo($playerId, $area ?:0);
        $areaInfo = \App\Models\Area::areaInfo($area);

        $data = ['command' => 'proc', 'dataCnt' => 114001100,'dataCnt' => $thew];
        $notify = \App\Models\Account\Thew::orgNotifyData($playerInfo, $data);

        \App\Models\Account\Thew::notifyGame($notify);

        \Log::debug('org notify thew', [$data]);
        $res['code'] = 0;
        return redirect('/admin/home/redirect?code=0&redirect='.url()->to('/admin/').'');
        //return response($res, 200)->header('Content-Type', 'application/json');
    }

    public function testOnlinePlayer()
    {
        $req_param = Input::all();
        return Admin::content(function (Content $content)use($req_param) {

            $content->header('testOnline form');
            $content->description('线上玩家统计');
            $server = $_SERVER['REQUEST_URI'];
            $content->row(Html::append([
                Html::input('area', 'area', url()->current()),
                Html::button('GO', url()->current(), 'search-filter'),
                Html::sjs(url()->current()),
                Html::button('echart',"/admin/player/view?area=".$req_param['area'],'btn-goto')
            ]));


            $grid = Admin::grid(PlayerOnline::class, function(Grid $grid){

                $grid->actions(function($actions){
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->append('<a href="'.url('admin/player/show?accountId='). $actions->row->account .'"><i class="glyphicon glyphicon-eye-open"></i></a>');
                });


                //$grid->account('account');
                //$grid->model()->orderBy('account', 'DESC');


                $grid->column('playerId');
                $grid->column('diamond');
                $grid->column('name');
                $grid->column('level');
                $grid->vip('Vip');
                $grid->column('ticket');
                $grid->column('account');
                // $grid->column('service_id');
                $grid->is_robot('Robot');
                
                $grid->filter(function ($filter){

                    $filter->like('area', 'area')->placeholder('');//

                });
            });
            $content->row($grid->render());
        });

    }
    public function view(Request $request){
        $area = $request->get('area');
        return Admin::content(function (Content $content) use($area){
            $content->header('Area Online Player');
            $content->description('各区服实时在线玩家');

            $content->row(view('admin.charts.test_echart',['area'=>$area]));

        });
    }

    // 禁言视图
    public function anyDisableChat(){
        return Admin::content(function($content){
            $content->header('disable chat manager');
            $content->description('.....');

            $get = Input::all();

            $form = new Form();
            $form->divide();
            $form->text('playerId', '用户playerid')->rules('required|min:3')->help('请在玩家管理地方搜索到palyerId 再传到这里')->default($get['playerId']?:'');
            $form->text('area', '玩家所在的区域')->help('是玩家所在区域，必选项')->default($get['area']?:'');
            $form->number('timestamp', '禁言时长')->rules('required|min:3');
            $form->hidden('_token', '_token')->default(csrf_token());
            $form->action('/admin/player/api-disable-chat');
            // $form->disablePajax();

            $content->row($form);
        });
    }

    // gm 禁言
    public function apiDisableChat() {
        $req = Input::all();
        \App\Models\Account\PlayerActModel::DisableChat($req['area'], $req['playerId'], $req['timestamp']);
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('send command success'.$req['timestamp'],'success'), 'data' =>[]]);

    }

    // gm 封号解封 角色
    public function apiRoleSeal() {
        $req = Input::all();
        \App\Models\Account\PlayerActModel::RoleSeal($req['area'], $req['playerId'], $req['role_seal']);
        //echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('send command success'.$req['role_seal'],'success'), 'data' =>[]]);

        return redirect('/admin/player/show?accountId='. $req['account']);
    }


    public function fetchData(Request $request){
        $area = $request->get('area');
        $info = PlayerOnline::GetOnlinePlayerList($area);
        $data[] = $info['data']['count'];
        if(count($data)==0){
            $data[] = 0;
        }
        date_default_timezone_set('PRC');
        array_unshift($data,date('H:i:s',time()));
        return $data;
    }

    // 玩家行为日志
    public function anyPlayerBehavior() {
        return Admin::content(function (Content $content) {

            $content->header('player log detail');
            $content->description('.....');

            $grid = Admin::grid(Behavior::class, function(Grid $grid){
                $grid->id('# ID');
                $grid->column('player_id');
                $grid->op('op');
                $grid->op_alias('op_alias');
                $grid->op_module('op_module');
                $grid->op_m_alias('ModuleAlias');
                $grid->column('level');
                $grid->column('diamond');
                $grid->op_val_1('Value1');
                $grid->item_alias('ItemAlias');
                $grid->op_val_2('Value2');
                $grid->op_val_3('Value3');
                $grid->op_time('Time')->display(function($value) {
                    return date("Y-m-d H:i:s", $value);
                });
                $grid->filter(function ($filter){
                    $filter->equal('player_id', 'PlayerID');
                    $filter->equal('area', 'Area')->select(\App\Models\Area::areaSelectData(0));//
                    $filter->in('ops', 'Operator')->multipleSelect(\App\Models\Account\Behavior::getOpAlias());
                    $filter->in('op_module', 'Modules')->multipleSelect(\App\Models\Account\Behavior::getOpmoduleAlias());
                    $filter->between('op_time', 'Operator Time')->datetime();
                });
            });

            $content->row($grid->render());
        });       
    }

    public function anyPromoteGm(Request $request) {
        $req = Input::all();
        \App\Models\Account\PlayerActModel::PromoteGm($req['area'], $req['player_id'], $req['gm_value']);
    }
    // 保存并发送体力给 game server
    public function apiClearRank(){
        $res = Input::all();
        $playerId = intval($res['playerId']);
        $area = intval($res['area']);

        \App\Models\Account\PlayerActModel::clearRank($area, $playerId, $req['gm_value']);

        \Log::debug('org clear rank', [$data]);
        $res['code'] = 0;
        return redirect('/admin/home/redirect?code=0&redirect='.url()->to('/admin/').'');
        //return response($res, 200)->header('Content-Type', 'application/json');
    }

    // 删除账号信息
    public function apiDeleteAccount() {
        $res = Input::all();
        $account = intval($res['account']);
        \App\Models\AccountInfo::deleteAccount($account);
        return redirect('/admin/home/redirect?code=0&redirect='.url()->to('/admin/').'');
    }

    // 封锁设备
    public function apiEncloseDevice() {
        $res = Input::all();
        $account = intval($res['account']);
        $deleted_at = isset($res['deleted_at']) ? intval($res['deleted_at']) : 2;
        \App\Models\AccountInfo::encloseAccount($account, $deleted_at);
        return redirect('/admin/home/redirect?code=0&redirect='.url()->to('/admin/').'');
    }
}

